// 渲染系统
class RenderSystem {
    constructor(world, canvas) {
        this.world = world;
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');
        this.scaleRatio = 1; // 缩放比例
        this.offsetX = 0; // 水平偏移量，用于居中地图
        this.offsetY = 0; // 垂直偏移量，用于跟随坦克
    }
    
    // 画布大小调整时调用
    onCanvasResize() {
        // 重新计算缩放比例
        this.scaleRatio = this.canvas.width / 1600; // 基于1600px的标准宽度计算缩放比例
        
        // 计算水平偏移量，使地图居中
        const mapWidth = this.world.getMapWidth();
        this.offsetX = Math.max(0, (this.canvas.width - mapWidth) / 2);
        console.log('Canvas resized. Width:', this.canvas.width, 'Map width:', mapWidth, 'Offset:', this.offsetX);
    }

    // 更新系统
    update(deltaTime) {
        // 更新摄像机位置，跟随本地玩家的坦克
        this.updateCameraPosition();
        
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 将偏移量传递给canvas上下文，供实体渲染时使用
        this.ctx.canvas.offsetX = this.offsetX;
        this.ctx.canvas.offsetY = this.offsetY;
        
        // 绘制背景
        this.renderBackground();
        
        // 绘制墙壁
        this.renderWalls();
        
        // 绘制坦克
        this.renderTanks();
        
        // 绘制子弹
        this.renderBullets();
        
        // 绘制UI元素
        this.renderUI();
    }
    
    // 更新摄像机位置
    updateCameraPosition() {
        const localTank = this.world.getLocalTank();
        if (!localTank) return;
        
        const mapWidth = this.world.getMapWidth();
        const mapHeight = this.world.getMapHeight();
        const viewportWidth = this.canvas.width;
        const viewportHeight = this.canvas.height;
        
        // 计算坦克中心位置
        const tankCenterX = localTank.x + localTank.width / 2;
        const tankCenterY = localTank.y + localTank.height / 2;
        
        // 计算理想的摄像机位置（使坦克居中）
        let idealOffsetX = viewportWidth / 2 - tankCenterX;
        let idealOffsetY = viewportHeight / 2 - tankCenterY;
        
        // 限制摄像机不超出地图边界
        // X轴限制
        this.offsetX = Math.min(0, Math.max(viewportWidth - mapWidth, idealOffsetX));
        
        // Y轴限制 - 修复摄像机跟随问题
        this.offsetY = Math.min(0, Math.max(viewportHeight - mapHeight, idealOffsetY));
        
        // 调试信息
        console.log('Camera position updated:', {
            tankPosition: { x: localTank.x, y: localTank.y },
            offsetY: this.offsetY,
            viewportHeight,
            mapHeight
        });
    }
    
    // 绘制背景
    renderBackground() {
        this.ctx.fillStyle = '#EEEEEE';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
    
    // 绘制墙壁
    renderWalls() {
        const walls = this.world.getWalls();
        
        for (const wallId in walls) {
            const wall = walls[wallId];
            // 使用Wall类的render方法来渲染墙壁
            wall.render(this.ctx);
        }
    }
    
    // 绘制坦克
    renderTanks() {
        const tanks = this.world.getTanks();
        
        for (const tankId in tanks) {
            const tank = tanks[tankId];
            if (tank.active) {
                tank.render(this.ctx);
            }
        }
    }
    
    // 绘制子弹
    renderBullets() {
        const bullets = this.world.getBullets();
        
        for (const bulletId in bullets) {
            const bullet = bullets[bulletId];
            if (bullet.active) {
                bullet.render(this.ctx);
            }
        }
    }
    
    // 绘制UI元素
    renderUI() {
        // 设置字体和样式
        this.ctx.font = `${14 * this.scaleRatio}px Arial`;
        this.ctx.fillStyle = '#333';
        
        // 绘制半透明背景
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
        
        // 左上角信息背景 - 修改为上下两个垂直排列的矩形
        this.ctx.fillRect(10, 10, 120 * this.scaleRatio, 30 * this.scaleRatio); // 玩家信息背景
        this.ctx.fillRect(10, 50 * this.scaleRatio, 120 * this.scaleRatio, 30 * this.scaleRatio); // 房间信息背景
        
        // 右上角返回房间列表按钮背景
        this.ctx.fillRect(this.canvas.width - 110 * this.scaleRatio, 10, 100 * this.scaleRatio, 30 * this.scaleRatio);
        
        // 绘制文本
        this.ctx.fillStyle = '#333';
        
        // 获取玩家名称和房间ID
        const playerName = document.getElementById('playerName').textContent;
        const roomId = document.getElementById('roomId').textContent;
        
        // 绘制玩家信息 - 显示在第一个矩形中
        this.ctx.fillText(`玩家: ${playerName}`, 15, 30 * this.scaleRatio);
        
        // 绘制房间信息 - 显示在第二个矩形中（垂直排列）
        this.ctx.fillText(`房间: ${roomId}`, 15, 70 * this.scaleRatio);
        
        // 绘制返回按钮
        this.ctx.fillText('返回房间列表', this.canvas.width - 100 * this.scaleRatio, 30 * this.scaleRatio);
        
        // 添加返回按钮的点击区域（不可见）
        if (!this.hasAddedBackButtonListener) {
            this.addBackButtonListener();
            this.hasAddedBackButtonListener = true;
        }
    }
    
    // 添加返回按钮的点击监听
    addBackButtonListener() {
        this.canvas.addEventListener('click', (event) => {
            // 获取点击坐标
            const rect = this.canvas.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;
            
            // 检查是否点击了返回按钮区域
            if (x >= this.canvas.width - 110 * this.scaleRatio && 
                x <= this.canvas.width - 10 * this.scaleRatio && 
                y >= 10 && 
                y <= 40 * this.scaleRatio) {
                // 返回房间列表
                window.location.href = '/rooms.html';
            }
        });
    }
}

// 如果在浏览器环境中，将RenderSystem添加到window对象
if (typeof window !== 'undefined') {
    window.RenderSystem = RenderSystem;
}

// 如果在Node.js环境中，导出RenderSystem类
if (typeof module !== 'undefined' && module.exports) {
    module.exports = RenderSystem;
}